在编写shell脚本时,通常最开始的工作是对环境的检查,比如检查某一文件或目录是否存在,并执行相应的操作等。下面的shell脚本实现的功能是,先检查某一目录是否存在,不存在的话就创建此目录,存在的话就cd到这个目录下。
#!/bin/bash #指定用到的shell解释器
export myPath=/tmp/test #设置目录的值
if [[ ! -e ${myPath} ]]; #判断此目录是否不存在
then
mkdir $myPath; #不存在则创建并切换目录
cd $myPath;
else
cd $myPath; #存在则直接切换目录
fi
然后我们执行相应的命令
[root@redhatclient test]# pwd
/root/test
[root@redhatclient test]# ls /tmp |grep test
[root@redhatclient test]# sh sh1.sh
[root@redhatclient test]# pwd
/root/test
[root@redhatclient test]# ls /tmp |grep test
test
[root@redhatclient test]#
可以看到脚本可以实现我们预想的功能,但是有一点要说明,在shell里面切换的目录,在shell执行完之后并不会生效,因为sh sh1.sh这种方式是在当前的shell下生成了一个shell子进程,只对接下来的脚本生效,不会对父进程shell生效。如果想要对父进程shell生效,使用命令:
[root@redhatclient test]# source sh1.sh
[root@redhatclient test]# pwd
/tmp/test
[root@redhatclient test]#
|